<template>
  <keep-alive>
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item label="序列号">
                <a-input placeholder="请输入序列号" @keyup.enter="searchQuery" v-model="queryParam.unitsn"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a-button type="primary" @click="openRework" icon="highlight"
                        style="margin-left: 8px;background-color: #19c227;border-color: #24d032">校对</a-button>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>

        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="federationId"
          class="j-table-force-nowrap"
          :scroll="{x:true}"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type:'radio'}"
          :customRow="clickThenSelect"
          @change="handleTableChange">
          <template slot="lotno" slot-scope="text">
            <a style="color:blue" @click="clickLotNo(text)">{{ text }}</a>
          </template>
          <template slot="htmlSlot" slot-scope="text">
            <div v-html="text"></div>
          </template>
          <template slot="imgSlot" slot-scope="text,record">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
            <img
              v-else
              :src="getImgView(text)"
              :preview="record.id"
              height="25px"
              alt=""
              style="max-width:80px;font-size: 12px;font-style: italic;" />
          </template>
          <template slot="fileSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
            <a-button
              v-else
              :ghost="true"
              type="primary"
              icon="download"
              size="small"
              @click="downloadFile(text)">
              下载
            </a-button>
          </template>
        </a-table>
      </div>

      <a-tabs defaultActiveKey="1" :activeKey="tabsModel" @change="tabsChange">
        <a-tab-pane tab="产品生产历史" key="1">
          <MesUnitHistoryList :mainId="selectedMainId" :line="line" @itemclick="cpnclick" />
        </a-tab-pane>
        <a-tab-pane tab="产品不良明细" key="2">
          <MesProcDataValueList :mainId="procDataMainId" />
        </a-tab-pane>
      </a-tabs>
      <!--      <a-tabs defaultActiveKey="1" :style="{width:rightWidth,float:'right'}">-->
      <!--        <a-tab-pane tab="参数明细" key="1">-->
      <!--          <MesProcDataValueList :mainId="procDataMainId" />-->
      <!--        </a-tab-pane>-->
      <!--        <a-tab-pane v-if="isNok" tab="故障明细" key="2" forceRender>-->
      <!--          <MesStatusWordValueList :mainId="procDataMainId" />-->
      <!--        </a-tab-pane>-->
      <!--      </a-tabs>-->
      <a-modal
        :title="title"
        :width="800"
        :visible="visible"
        :confirmLoading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
        cancelText="关闭">
        <a-spin :spinning="confirmLoading">
          <a-form-model ref="form" :label-col="labelCol" :wrapper-col="wrapperCol" :model="model">
            <a-form-model-item label="工站" prop="op">
              <a-select placeholder="请选择工站" v-model="model.op" @change="opChange">
                <a-select-option :value="undefined">请选择</a-select-option>
                <a-select-option v-for="(item, key) in opOptions" :key="key" :value="item.op">
                  <span style="display: inline-block;width: 100%" :title=" item.op">
                    {{ item.description + '-' + item.op }}
                  </span>
                </a-select-option>
              </a-select>
            </a-form-model-item>

            <a-form-model-item label="缺陷描述" prop="cfgid">
              <a-select
                v-model="model.cfgid"
                show-search
                placeholder="缺陷描述"
                :options="cfgOptions"
                :filter-option="filterOption"
                @change="handleChange"
              ></a-select>
            </a-form-model-item>

            <a-form-model-item label="处理方案" prop="typ">
              <a-radio-group v-model="model.typ" button-style="solid" @change="typeChange">
                <a-radio-button value="1">返工</a-radio-button>
                <a-radio-button value="2">跳站</a-radio-button>
                <a-radio-button value="3">报废</a-radio-button>
                <a-radio-button value="4" checked>待定</a-radio-button>
              </a-radio-group>
            </a-form-model-item>
            <a-form-model-item label="代号选择" prop="code">
              <a-select placeholder="请选择工站" v-model="model.code" @change="codeChange">
                <a-select-option :value="undefined">请选择</a-select-option>
                <a-select-option v-for="(item, key) in rwkOptions" :key="key" :value="item.code">
                  <span style="display: inline-block;width: 100%" :title="item.code">
                    {{ item.code }}
                  </span>
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </a-spin>
      </a-modal>
    </a-card>
  </keep-alive>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { downFile, getAction, httpAction } from '@/api/manage'
import MesUnitHistoryList from '../trace/modules/MesUnitHistoryList.vue'
import MesMaterialSetProductList from '../trace/modules/MesMaterialSetProductList.vue'
import MesProcDataValueList from '../trace/modules/MesProcDataValueList.vue'
import MesStatusWordValueList from '../trace/modules/MesStatusWordValueList.vue'
import MesUnitidList from '../trace/modules/MesUnitidList.vue'
import QualityReworkModal from '../trace/modules/QualityReworkModal.vue'
import '@/assets/less/TableExpand.less'

export default {
  barcode: '',
  name: 'QualityRework',
  mixins: [JeecgListMixin],
  components: {
    MesUnitHistoryList,
    MesUnitidList,
    MesProcDataValueList,
    MesStatusWordValueList,
    QualityReworkModal,
    MesMaterialSetProductList
  },
  data() {
    return {
      description: '序列号列表管理页面',
      title: '操作',
      label: '',
      opOptions: [],
      cfgOptions: [],
      cfgOptionDetails: [],
      rwkOptions: [],
      visible: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {
        line: '',
        typ: '4'
      },
      validatorRules: {
        code: [
          { required: true, message: '请选择方案!' }
        ]
      },
      // 表头
      queryParam: {
        unitsn: this.$route.query.unitsn
      },
      isNok: false,
      oneLoad: 1,
      leftWidth: '65%',
      rightWidth: '35%',
      columns: [
        {
          title: '工单ID',
          align: 'center',
          dataIndex: 'woid'
        },
        {
          title: '序列号',
          align: 'center',
          dataIndex: 'unitsn'
        },
        {
          title: '产品码',
          align: 'center',
          dataIndex: 'product'
        },
        {
          title: '产品或产品组',
          align: 'center',
          dataIndex: 'partno'
        },
        {
          title: '产线或产线组',
          align: 'center',
          dataIndex: 'line'
        },
        {
          title: '工位',
          align: 'center',
          dataIndex: 'op'
        },
        {
          title: '工站',
          align: 'center',
          dataIndex: 'stn'
        },
        {
          title: '盒号',
          align: 'center',
          dataIndex: 'lotno',
          scopedSlots: { customRender: 'lotno' }
        },
        {
          title: '日期',
          align: 'center',
          dataIndex: 'dt',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '结果',
          align: 'center',
          dataIndex: 'result_dictText'
        },
        {
          title: '重复加工次数',
          align: 'center',
          dataIndex: 'repeatCount'
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText'
        },
        {
          title: '班次日期',
          align: 'center',
          dataIndex: 'shiftDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '班次',
          align: 'center',
          dataIndex: 'shift'
        },
        {
          title: '产线类型',
          align: 'center',
          dataIndex: 'segmentCode_dictText'
        },
        {
          title: '更新时间',
          align: 'center',
          dataIndex: 'ctime'
        }
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   align: 'center',
        //   fixed: 'right',
        //   width: 147,
        //   scopedSlots: { customRender: 'action' }
        // }
      ],
      url: {
        list: '/trace/barcodeTrace/queryByCode',
        rwkList: '/qis/mesRwkCodeCfg/list',
        cfgList: '/qis/qisReinspectCfg/list',
        getOpSelect: '/basic/mesLineOpCfg/opSelect',
        exportXlsUrl: '/trace/barcodeTrace/exportXls'
      },
      runCmd: '/monitor/api/runCmd',
      dictOptions: {},
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      selectedMainId: '',
      line: '',
      op: '',
      procDataMainId: '',
      tabsModel: '1',
      superFieldList: []
    }
  },
  created() {
    console.log('页面初始化666')
    // this.getSuperFieldList()
  },
  computed: {

    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }

  },
  watch: {
    line(val) {
      console.log('产线改变')
      if (val) {
        getAction(this.url.getOpSelect, { line: val }).then((res) => {
          if (res.success) {
            this.opOptions = res.result
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
        })
      } else {
        this.opOptions = []
        this.value = ''
      }
    }
  },
  methods: {
    codeChange() {
      console.log('当前model1')
      console.log(this.model)
    },
    typeChange(val) {
      console.log('当前model2')
      console.log(this.model)
    },
    opChange(val) {
      //清空下边所有选项
      this.model.cfgid = ''
      this.model.typ = null
      this.model.code = null
      this.op = val
      //访问对应产线对应工站的所有故障描述并展示
      let param = {
        line: this.line,
        op: this.op,
        pageNo: 1,
        pageSize: 100
      }
      getAction(this.url.cfgList, param).then((res) => {
        //将数据存放在数组中
        let option = []
        res.result.records.map(item => {
          option.push({
            value: item.recId,
            label: item.description
          })
        })
        this.cfgOptions = option
        this.cfgOptionDetails = res.result.records
      })
      //请求对应返工代码
      this.getRwkList('')
    },
    handleChange(value) {
      this.model.typ = ''
      this.model.code = ''
      this.cfgOptionDetails.map(item => {
        if (item.recId === value) {
          this.model.typ = item.type + ''
          this.getRwkList(item.type)
        }
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.indexOf(input) !== -1
    },
    openRework(record) {
      this.visible = true
      console.log('打开返工弹窗')
      console.log(this.dataSource)
      this.model.line = this.dataSource[0].line
      this.label = '返工'
    },
    getRwkList(typ) {
      console.log('查看op')
      console.log(this.op)
      let param = {
        line: this.line,
        op: this.op,
        pageNo: 1,
        pageSize: 100
      }
      if (typ) {
        param.type = typ
      }
      getAction(this.url.rwkList, param).then((res) => {
        this.rwkOptions = res.result.records
        if (this.rwkOptions.length === 1) {
          this.model.code = this.rwkOptions[0].code
        }
      })
    },
    handleOk() {
      this.load = {
        serviceid: 'mes',
        cmd: 'rework',
        entityid: this.selectedMainId,
        clientid: this.line + ';;',
        code: this.model.code
      }
      httpAction(this.runCmd, this.load, 'post').then((res) => {
        console.log('返回结果')
        console.log(res)
        if (res.success) {
          this.isResult = this.product.result
        } else {
          this.isResult = this.product.result
        }
      }).finally(() => {
        this.rwkOptions = []
        this.visible = false
      })

    },
    handleCancel() {
      this.rwkOptions = []
      this.op = ''
      this.model = {}
      this.visible = false
    },
    clickLotNo(val) {
      this.$router.push({ path: './MesLotStatusList', query: { lotNo: val } })
    },
    handleExportXls(fileName, record) {
      if (!fileName || typeof fileName !== 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, record).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
    },
    initDictConfig() {
    },
    searchQuery() {
      if (this.queryParam.unitsn.split(';').length > 1) {
        let arr = this.queryParam.unitsn.split(';')
        this.queryParam.unitsn = arr[arr.length - 2]
      } else if (this.queryParam.unitsn.split('  ').length > 1) {
        let arr = this.queryParam.unitsn.split('  ')
        this.queryParam.unitsn = arr[arr.length - 2]
      } else {
      }
      let record = this.dataSource[0]
      this.model = {}
      if (record) {
        this.line = record.line
        this.op = record.op
        this.selectedMainId = record.unitsn
      }
      this.loadData(1)
      //this.onSelectChange(record.federationId.split(','), [record])
    },
    clickThenSelect(record) {
      return {
        on: {
          click: () => {
            //存储当前工站信息获取返工代码列表
            this.onSelectChange(record.federationId.split(','), [record])
          }
        }
      }
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
      this.selectedMainId = ''
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.line = selectionRows[0].line
      this.op = selectionRows[0].op
      this.selectedMainId = selectionRows[0].unitsn

      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.onClearSelected()
      var params = this.getQueryParams()// 查询条件
      if (this.oneLoad === 1) {
        this.oneLoad = 2
      } else {
        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.line = res.result.records[0].line
            this.ipagination.total = res.result.total
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      }
    },
    tabsChange(key) {
      this.tabsModel = key
      if (key === '2') {
        this.leftWidth = '100%'
        this.rightWidth = '0%'
      } else {
        this.leftWidth = '65%'
        this.rightWidth = '35%'
      }
    },
    cpnclick(item) {
      this.procDataMainId = item.recId
      if (item.result === '2') {
        this.isNok = true
      } else {
        this.isNok = false
      }
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'woid', text: '工单ID', dictCode: '' })
      fieldList.push({ type: 'string', value: 'unitsn', text: '序列号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'partno', text: '产品或产品组', dictCode: '' })
      fieldList.push({ type: 'string', value: 'line', text: '产线或产线组', dictCode: '' })
      fieldList.push({ type: 'string', value: 'op', text: '工位', dictCode: '' })
      fieldList.push({ type: 'string', value: 'stn', text: '工站', dictCode: '' })
      fieldList.push({ type: 'date', value: 'dt', text: '日期' })
      fieldList.push({ type: 'string', value: 'result', text: '9=Default,0=Loaded,1=OK,2=NOK', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'repeatCount', text: '重复加工次数', dictCode: '' })
      fieldList.push({
        type: 'string',
        value: 'status',
        text: '0: Init, 1: WIP, 2: FG, 3: Rework, 5: Scrap, 6:On Hold,7: InterFG,8: CheckPart',
        dictCode: ''
      })
      fieldList.push({ type: 'date', value: 'shiftDate', text: '班次日期' })
      fieldList.push({ type: 'string', value: 'shift', text: '班次', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwktoOp', text: '返工至工位', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwktoStn', text: '返工至工站', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'cycleId', text: '运行周期ID', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'parttypeid', text: '产品ID', dictCode: '' })
      fieldList.push({ type: 'BigDecimal', value: 'statusword', text: '状态字', dictCode: '' })
      fieldList.push({ type: 'string', value: 'segmentCode', text: '0:主线  1:1号支线 2:2号支线', dictCode: '' })
      fieldList.push({ type: 'string', value: 'rwkCode', text: '返工代码', dictCode: '' })
      fieldList.push({ type: 'string', value: 'lotno', text: '是否成批', dictCode: '' })
      fieldList.push({ type: 'date', value: 'ctime', text: '更新时间' })
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
